//Mark O Meara
//08332240

import java.util.Vector;
import tcdIO.*;

public class Channel {
	Terminal terminal1 = new Terminal(Channel.class.getName());
	public static int BUFFERSIZE= 10;  // number of simultaneous frames 
	
	Vector<byte[]> frames= null; 		// Buffer for frames
	int noise;						// Noise applied to transmissions
	
	/*
	 * Empty constructor for channel
	 */
	Channel() {
		this(BUFFERSIZE);//Calls Channel(int count) constructor
	}
	
	/**
	 * Constructor that accepts the number of simultaneous frames.
	 * 
	 * @param count Number of simultaneous frames in the channel
	 */
	Channel(int count) {
		this(count, 30);// Calls Channel(int count, int noise) constructor
	}

	/*
	 * Constructor that accepts the number of simultaneous frames
	 * and the noise applied to transmissions.
	 */
	Channel(int count, int noise) {
		frames= new Vector<byte[]>(BUFFERSIZE);
		this.noise= noise;
	}
	
	
	/*
	 * Sends a frame through the channel.
	 */
	public synchronized void send(byte[] frame) {
		if (frames.size()<BUFFERSIZE){//If there is space in vector to store frames
			if ((Math.random()*100)>noise) {    // if the signal is stronger than the noise
				frames.add(frame);              // transmit the frame
				notifyAll();//Wakes up all threads that called wait()
				try {
					wait(1000);
				}
				catch(Exception e){
					e.printStackTrace();
				}
			}
			else {
				terminal1.println("Frame lost due to noise");	// debug info
			}
		}
	}
	
	
	/*
	 * Attempts to receive a frame from the channel.
	 */
	public synchronized byte[] receive() {
		byte[] frame= null;
		
		try {
			while (frames.size()<1) {
				wait(5);
			}	// check every 5 ms if a frame is available
		} 
		catch(Exception e) {
			e.printStackTrace();
		}
		frame= frames.remove(0);					// take frame from channel and return it
		return frame;
	}
}